"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : Compatibility
Case Name   : 当前用户为Sysadmin,set password指定user的不同形式
Create At   : 2022/08/18
@zou_jialiang0501162243
Description :
        1.创建用户
        2.user参数形式为user，大小写和已存在用户一致
        3.user参数形式为user，大小写和已存在用户不一致
        4.user参数形式为'user'，大小写和已存在用户一致
        5.user参数形式为'user'，大小写和已存在用户不一致
        6.user参数形式为"user"，大小写和已存在用户一致
        7.user参数形式为"user"，大小写和已存在用户不一致
        8.user参数形式为user@'host',大小写和已存在用户一致
        9.user参数形式为user@'host'，大小写和已存在用户不一致
        10.user参数形式为'user'@'host'，大小写和已存在用户一致
        11.user参数形式为'user'@'host'，大小写和已存在用户不一致
        12.user参数形式为"user"@'host'，大小写和已存在用户一致
        13.user参数形式为"user"@'host'，大小写和已存在用户不一致
Expect      :
        1.用户创建成功
        2.修改成功
        3.修改成功
        4.修改成功
        5.合理报错
        6.修改成功
        7.合理报错
        8.修改成功
        9.修改成功
        10.修改成功
        11.合理报错
        12.修改成功
        13.合理报错
History     :
    modified by @zou_jialiang050,2023.01.18，添加step6的log信息记录，修改指定数据库
    modified by @zou_jialiang050,2023.03.21，修改guc参数设置命令删除single=TRUE选项&&
    增加test_user_host参数控制，规避其他功能影响&&适配server新特性
    modified by @zou_jialiang050,2023.03.24，研发代码变更，参数名称变更
"""
import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class ClientConnection(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.common = Common()
        self.constant = Constant()
        self.sh_primary = CommonSH('PrimaryDbUser')
        self.primary = Node('PrimaryDbUser')
        self.us_name1 = 'us_setpassword0021'
        self.us_name2 = 'US_SETPASSWORD0021'
        self.passwd1 = 'qwertyuiop'
        self.passwd2 = 'abcdefg'
        self.db_name = 'db_setpassword0021'
        self.einfo = 'ERROR:  Permission denied.'
        text1 = '--------修改密码复杂度策略   expect:修改成功--------'
        self.log.info(text1)
        self.pwd_1 = self.common.show_param('password_policy')
        res1 = self.sh_primary.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             'password_policy=0')
        self.log.info(res1)
        self.assertTrue(res1, '执行失败' + text1)
        text2 = '--------修改可重用天数为0   expect:修改成功--------'
        self.log.info(text2)
        self.pwd_2 = self.common.show_param('password_reuse_time')
        res2 = self.sh_primary.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             'password_reuse_time=0')
        self.log.info(res2)
        self.assertTrue(res2, '执行失败' + text2)
        text3 = '--------重启数据库   expect:重启成功--------'
        self.log.info(text3)
        res3 = self.sh_primary.restart_db_cluster()
        self.log.info(res3)
        self.assertTrue(res3, '执行失败' + text3)

    def test_set_password(self):
        text = '--------step1:创建用户和兼容b库   expect:创建成功--------'
        self.log.info(text)
        create_user = f"drop user if exists {self.us_name1};" \
                      f"create user {self.us_name1} " \
                      f"password '{self.passwd1}';"
        res = self.sh_primary.execut_db_sql(create_user)
        self.log.info(res)
        self.assertIn(self.constant.CREATE_ROLE_SUCCESS_MSG, res, res)
        create_db = f"drop database if exists {self.db_name};" \
                    f"create database {self.db_name} dbcompatibility='B';" \
                    f"\c {self.db_name}"
        res0 = self.sh_primary.execut_db_sql(create_db)
        self.log.info(res0)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, res0, res0)

        text = '--------step2:user参数形式为user，大小写和已存在用户一致   ' \
               'expect:修改成功--------'
        self.log.info(text)
        sql_cmd1 = f"set password for {self.us_name1} = '{self.passwd2}' " \
                   f"replace '{self.passwd1}';"
        res1 = self.sh_primary.execut_db_sql(sql=sql_cmd1,
                                             sql_type=f'-U {self.us_name1} '
                                                      f'-W {self.passwd1}',
                                             dbname=self.db_name)
        self.log.info(res1)
        self.assertEqual(self.constant.ALTER_ROLE_SUCCESS_MSG, res1, res1)

        text = '--------step3:user参数形式为user，大小写和已存在用户不一致   ' \
               'expect:修改成功--------'
        self.log.info(text)
        sql_cmd2 = f"set password for {self.us_name2} = '{self.passwd1}' " \
                   f"replace '{self.passwd2}';"
        res2 = self.sh_primary.execut_db_sql(sql=sql_cmd2,
                                             sql_type=f'-U {self.us_name1} '
                                                      f'-W {self.passwd2}',
                                             dbname=self.db_name)
        self.log.info(res2)
        self.assertEqual(self.constant.ALTER_ROLE_SUCCESS_MSG, res2, res2)

        text = "--------step4:user参数形式为'user'，大小写和已存在用户一致   " \
               "expect:修改成功--------"
        self.log.info(text)
        sql_cmd3 = f"set b_compatibility_user_host_auth=on;" \
                   f"set password for '{self.us_name1}' = '{self.passwd2}'" \
                   f" replace '{self.passwd1}';"
        res3 = self.sh_primary.execut_db_sql(sql=sql_cmd3,
                                             sql_type=f'-U {self.us_name1} '
                                                      f'-W {self.passwd1}',
                                             dbname=self.db_name)
        self.log.info(res3)
        self.assertIn(self.constant.SET_SUCCESS_MSG, res3, res3)
        self.assertIn(self.constant.ALTER_ROLE_SUCCESS_MSG, res3, res3)

        text = "--------step5:user参数形式为'user'，大小写和已存在用户不一致   " \
               "expect:合理报错--------"
        self.log.info(text)
        sql_cmd4 = f"set b_compatibility_user_host_auth=on;" \
                   f"set password for '{self.us_name2}' = '{self.passwd1}'" \
                   f" replace '{self.passwd2}';"
        res4 = self.sh_primary.execut_db_sql(sql=sql_cmd4,
                                             sql_type=f'-U {self.us_name1} '
                                                      f'-W {self.passwd2}',
                                             dbname=self.db_name)
        self.log.info(res4)
        self.assertIn(self.constant.SET_SUCCESS_MSG, res4, res4)
        self.assertIn(self.einfo, res4, res4)

        text = '--------step6:user参数形式为"user"，' \
               '大小写和已存在用户一致   ' \
               'expect:修改成功--------'
        self.log.info(text)
        sql_cmd5 = f"""source {macro.DB_ENV_PATH};\
        gsql -d {self.db_name} -p \
        {self.sh_primary.node.db_port} -U {self.us_name1} -W {self.passwd2} \
        -c 'set password for "{self.us_name1}" = "{self.passwd1}" \
        replace "{self.passwd2}";'"""
        self.log.info(sql_cmd5)
        res5 = self.sh_primary.node.sh(sql_cmd5).result()
        self.log.info(res5)
        self.assertEqual(self.constant.ALTER_ROLE_SUCCESS_MSG, res5, res5)

        text = '--------step7:user参数形式为"user"，' \
               '大小写和已存在用户不一致   ' \
               'expect:合理报错--------'
        self.log.info(text)
        sql_cmd6 = f"""source {macro.DB_ENV_PATH}; \
        gsql -d {self.db_name} -p \
        {self.sh_primary.node.db_port} -U {self.us_name1} -W {self.passwd1} \
        -c 'set password for "{self.us_name2}" = "{self.passwd2}" \
        replace "{self.passwd1}";'"""
        self.log.info(sql_cmd6)
        res6 = self.sh_primary.node.sh(sql_cmd6).result()
        self.log.info(res6)
        self.assertEqual(self.einfo, res6, res6)

        text = "--------step8:user参数形式为user@'host',大小写和已存在用户" \
               "一致   expect:合理报错--------"
        self.log.info(text)
        sql_cmd7 = f"set b_compatibility_user_host_auth=on;" \
                   f"set password for " \
                   f"{self.us_name1}@'{self.sh_primary.node.db_host}' = " \
                   f"'{self.passwd2}' replace '{self.passwd1}';"
        self.log.info(sql_cmd7)
        res7 = self.sh_primary.execut_db_sql(sql=sql_cmd7,
                                             sql_type=f'-U {self.us_name1} '
                                                      f'-W {self.passwd1}',
                                             dbname=self.db_name)
        self.log.info(res7)
        self.assertIn(self.constant.SET_SUCCESS_MSG, res7, res7)
        self.assertIn(self.einfo, res7, res7)

        text = "--------step9:user参数形式为user@'host',大小写和已存在用户" \
               "不一致   expect:合理报错--------"
        self.log.info(text)
        sql_cmd8 = f"set b_compatibility_user_host_auth=on;" \
                   f"set password for " \
                   f"{self.us_name2}@'{self.sh_primary.node.db_host}' = " \
                   f"'{self.passwd1}' replace '{self.passwd2}';"
        res8 = self.sh_primary.execut_db_sql(sql=sql_cmd8,
                                             sql_type=f'-U {self.us_name1} '
                                                      f'-W {self.passwd1}',
                                             dbname=self.db_name)
        self.log.info(res8)
        self.assertIn(self.constant.SET_SUCCESS_MSG, res8, res8)
        self.assertIn(self.einfo, res8, res8)

        text = "--------step10:user参数形式为'user'@'host'，" \
               "大小写和已存在用户一致" \
               "   expect:合理报错--------"
        self.log.info(text)
        sql_cmd9 = f"set b_compatibility_user_host_auth=on;" \
                   f"set password for " \
                   f"'{self.us_name1}'@'{self.sh_primary.node.db_host}' = " \
                   f"'{self.passwd2}'replace '{self.passwd1}';"
        res9 = self.sh_primary.execut_db_sql(sql=sql_cmd9,
                                             sql_type=f'-U {self.us_name1} '
                                                      f'-W {self.passwd1}',
                                             dbname=self.db_name)
        self.log.info(res9)
        self.assertIn(self.constant.SET_SUCCESS_MSG, res9, res9)
        self.assertIn(self.einfo, res9, res9)

        text = "--------step11:user参数形式为'user'@'host'，大小写和已存在用户" \
               "不一致   expect:合理报错--------"
        self.log.info(text)
        sql_cmd10 = f"set b_compatibility_user_host_auth=on;" \
                    f"set password for " \
                    f"'{self.us_name2}'@'{self.sh_primary.node.db_host}' = " \
                    f"'{self.passwd1}' replace '{self.passwd2}';"
        res10 = self.sh_primary.execut_db_sql(sql=sql_cmd10,
                                              sql_type=f'-U {self.us_name1} '
                                                       f'-W {self.passwd1}',
                                              dbname=self.db_name)
        self.log.info(res10)
        self.assertIn(self.constant.SET_SUCCESS_MSG, res10, res10)
        self.assertIn(self.einfo, res10, res10)

        text = '''--------step12:user参数形式为"user"@'host'，大小写和已存在用户 \
                一致   expect:合理报错--------'''
        self.log.info(text)
        sql_cmd11 = f"""source {macro.DB_ENV_PATH};\
        gsql -d {self.db_name} -p \
        {self.sh_primary.node.db_port} -U {self.us_name1} -W {self.passwd1} \
        -c 'set b_compatibility_user_host_auth=on;set password for \
        "{self.us_name1}"@"{self.sh_primary.node.db_host}" = \
        "{self.passwd1}" replace "{self.passwd2}";'"""
        res11 = self.sh_primary.node.sh(sql_cmd11).result()
        self.log.info(res11)
        self.assertIn(self.constant.SET_SUCCESS_MSG, res11, res11)
        self.assertIn("ERROR", res11, res11)

        text = '''--------step13:user参数形式为"user"@'host'，大小写和已存在用户 \
                不一致   expect:合理报错--------'''
        self.log.info(text)
        sql_cmd12 = f"""source {macro.DB_ENV_PATH};\
        gsql -d {self.db_name} -p \
        {self.sh_primary.node.db_port} -U {self.us_name1} -W {self.passwd1} \
        -c 'set b_compatibility_user_host_auth=on;set password for \
        "{self.us_name2}"@"{self.sh_primary.node.db_host}" = \
        "{self.passwd2}" replace "{self.passwd1}";'"""
        res12 = self.sh_primary.node.sh(sql_cmd12).result()
        self.log.info(res12)
        self.assertIn(self.constant.SET_SUCCESS_MSG, res12, res12)
        self.assertIn("ERROR", res12, res12)

    def tearDown(self):
        self.log.info('-----清理环境-----')
        text1 = '--------删除用户和兼容b库   expect:删除成功--------'
        self.log.info(text1)
        drop_cmd = f"drop user if exists {self.us_name1};"
        res = self.sh_primary.execut_db_sql(drop_cmd)
        self.log.info(res)
        res0 = self.sh_primary.execut_db_sql(f"drop database if exists "
                                             f"{self.db_name};")
        self.log.info(res0)
        text2 = '--------恢复默认密码复杂度策略   expect:修改成功--------'
        self.log.info(text2)
        res1 = self.sh_primary.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             f'password_policy = {self.pwd_1}')
        self.log.info(res1)
        text3 = '--------恢复默认可重用天数   expect:修改成功--------'
        self.log.info(text3)
        res2 = self.sh_primary.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             f'password_reuse_time = '
                                             f'{self.pwd_2}')
        self.log.info(res2)
        text4 = '--------重启数据库   expect:重启成功--------'
        self.log.info(text4)
        res3 = self.sh_primary.restart_db_cluster()
        self.log.info(res3)
        self.assertEqual(self.constant.DROP_ROLE_SUCCESS_MSG, res,
                         '执行失败' + text1)
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, res0,
                      '执行失败' + text1)
        self.assertTrue(res1, '执行失败' + text2)
        self.assertTrue(res2, '执行失败' + text3)
        self.assertTrue(res3, '执行失败' + text4)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
